<script lang="ts" setup>
const show = defineModel()

const emit = defineEmits(['close'])

// 监听 show 的变化来控制背景滚动
watch(show, newVal => {
  if (newVal) {
    // 显示遮罩时禁止背景滚动
    document.body.style.overflow = 'hidden'
  } else {
    // 关闭遮罩时恢复背景滚动
    document.body.style.overflow = ''
  }
})

const handleClick = () => {
  // 确保点击的是遮罩层本身而不是其内容
  emit('close')
  show.value = false
}
// 组件卸载时确保恢复滚动
onUnmounted(() => {
  document.body.style.overflow = ''
})
</script>
<template>
  <transition name="fade">
    <div v-show="show" class="overlay">
      <div class="overlay-content" @click.self="handleClick">
        <!-- 默认插槽 -->
        <slot name="header"></slot>
        <slot></slot>
        <slot name="footer"></slot>
      </div>
    </div>
  </transition>
</template>

<style scoped>
.overlay {
  position: fixed;
  inset: 0;
  display: flex;
  justify-content: center;
  z-index: 998;
  touch-action: none;
  align-items: flex-start;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(2px);
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
}

.overlay-content {
  position: relative;
  z-index: 1000;
  pointer-events: auto;
  /* 添加最大高度和滚动 */
  height: 100%;
  overflow-y: auto;
  overscroll-behavior: contain;
  width: 100%;
  padding: 20px 0;
}

/* 内容区域允许交互 */
.overlay-content > * {
  pointer-events: auto;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
